<script setup lang="ts">
import { setup } from "@/utils/setup.js";
import { useAsyncRef } from "@/utils/use";
import md5 from "crypto-js/md5";
import {
  NButton,
  NCard,
  NForm,
  NFormItem,
  NGradientText,
  NInput,
} from "naive-ui";
import { ref } from "vue";

const { masterStore, configStore, message, route, router } = setup();

const serverURL = ref(masterStore.serverURL);
const token = ref("");
const testLogin = useAsyncRef({
  supplier: masterStore.testLogin,
  onSuccess: () => {
    message.success("登录成功");
    router.push((route.query["redirect"] ?? "/") as string);
  },
  onError: (error) => message.error(error.toString()),
});

const defaultServerURL = `http://${location.hostname}:8787`;
async function login() {
  serverURL.value = serverURL.value || defaultServerURL;
  masterStore.serverURL = serverURL.value;
  masterStore.token = token.value !== "" ? md5(token.value).toString() : "";
  testLogin.execute();
}
</script>

<template>
  <div
    style="
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
    "
  >
    <NCard style="max-width: 400px; box-shadow: var(--n-box-shadow)">
      <template #header>
        <NGradientText
          style="width: 100%; text-align: center"
          :size="36"
          :gradient="{ from: 'purple', to: 'blue', deg: 30 }"
        >
        OhMyDev
        </NGradientText>
      </template>
      <NForm>
        <NFormItem label="服务器 URL">
          <NInput v-model:value="serverURL" :placeholder="defaultServerURL" />
        </NFormItem>
        <NFormItem label="Token">
          <NInput
            v-model:value="token"
            type="password"
            show-password-on="click"
          />
        </NFormItem>
        <NFormItem>
          <NButton
            style="margin-left: auto"
            attr-type="button"
            :disabled="configStore.cache.config.state.ready"
            @click="login"
          >
            登录
          </NButton>
        </NFormItem>
      </NForm>
    </NCard>
  </div>
</template>
